package spcpy

import (
	"fmt"
	"gitee.com/ymofen/gobase"
	"gitee.com/ymofen/gobase/factory"
	"gitee.com/ymofen/gobase/subpub"
	"gitee.com/ymofen/replay"
	"sync"
	"time"
)

type ReplayRecorder struct {
	startedflag int32
	taskId      string
	lk          sync.RWMutex
	ex          *subpub.Subchannel

	saveFmt string

	lastrecvT  time.Time
	statusText string
	recorder   *replay.TimeRotatingRecorder
}

func (this *ReplayRecorder) CheckStart() error {
	this.lk.Lock()
	defer this.lk.Unlock()
	if this.startedflag == 1 {
		return nil
	}
	rd := replay.NewTimeRotatingRecorder()
	rd.SetSaveFormat(this.saveFmt)
	this.recorder = rd
	defer func() {
		this.startedflag = 1
	}()

	return nil
}

func (this *ReplayRecorder) Sub(id, channel string, cb subpub.SubFunc) {
	this.ex.Sub(id, channel, cb)
}

func (this *ReplayRecorder) Unsub(id, channel string) bool {
	return this.ex.Unsub(id, channel)
}

func (this *ReplayRecorder) Pub(topic string, max int, args ...interface{}) int {
	var data []byte
	if buf, ok := args[0].([]byte); ok {
		data = buf
	} else if str, ok := args[0].(string); ok {
		data = []byte(str)
	} else {
		return -1
	}

	rd := this.recorder
	if rd != nil {
		rd.Write(data)
	}

	return int(1)
}

func (this *ReplayRecorder) Close() error {
	if this.startedflag == 1 {
		this.recorder.Close()
	}

	this.lk.Lock()
	this.ex = nil
	this.startedflag = 0
	this.lk.Unlock()

	return nil
}

func (this *ReplayRecorder) GetConnString() string {
	return ""
}

var (
	DefaultReplayRecorderNodes = gobase.NewConnectObjectRefStorage(newReplayRecorder)
)

func newReplayRecorder(connstr string) interface{} {
	node := &ReplayRecorder{
		ex: subpub.NewSubchannel(),
	}

	confMap := gobase.NewStrMap()
	confMap.URLFormDecode(connstr)
	saveFmt := confMap["saveFmt"]
	node.saveFmt = saveFmt
	return node
}

// conntype=replayRecorder&savefile=
func checkGetReplayRecorder(args ...interface{}) (rval interface{}, err error) {
	if len(args) == 0 {
		err = fmt.Errorf("无效的参数")
		return
	}
	if conf, ok := args[0].(gobase.StrMap); ok {
		s := conf.URLFormEncodeKeylst("saveFmt")
		rval = DefaultReplayRecorderNodes.CheckGetRef(s)
		return
	} else {
		err = fmt.Errorf("无效的参数")
		return
	}
}

func init() {

	factory.RegisterCreateFunc("sp.replayRecorder", checkGetReplayRecorder)
}
